import { useEffect, useRef, useState } from 'react';
import * as THREE from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'; // 使用正确的导入路径
import { useNavigate } from 'react-router';
import { GLTFExporter } from 'three/examples/jsm/exporters/GLTFExporter';
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader';
import Fzx from './fzx'; 
import Zjl from './ping.module.css';
import WidthHeigth from './zu/move';
import Heigths from './zu/hiey';
import Widths from './zu/wiex';
import Addkuan from './zu/addkuan';
import Xuankuan from './zu/xuankuan';
import Ban from './zu/banj';
import { ArrowLeft } from '@react-vant/icons';
import axios from 'axios';
import { log } from 'three/webgpu';
import tu from "./zu/tu.jpg"
axios.defaults.baseURL = 'http://localhost:3000/Niux'

let App = () => {
    let nav =useNavigate()
    const width = window.innerWidth - 100;
    const height = window.innerHeight - 40;
    const canvasRef = useRef(null); // 画布存放位置
    const sceneRef = useRef(new THREE.Scene()); // 创建一个场地
    const cameraRef = useRef(new THREE.PerspectiveCamera(30, width / height, 0.1, 5000)); // 创建相机锥体
    const rendererRef = useRef(new THREE.WebGLRenderer({ antialias: true })); // 创建渲染器
    const intersectsRef = useRef(null); // 被照射的物体
    const lastTouchX = useRef(0);
    const lastTouchY = useRef(0);
    const [state, setState] = useState('');
    const controlsRef = useRef(null); 
    const [imgSrc, setImgSrc] = useState('');
    let [accessToken, setaccessToken] = useState(JSON.parse(localStorage.getItem('accessToken')) || "")
    const getImg = async () => {
        const { data } = await axios.get("/getImg", {
            headers: {
                'Content-Type': 'multipart/form-data',
                'Authorization': accessToken
              }
        })
        setImgSrc( "http://127.0.0.1:3000/" + data.data.imgSrc);
            
    }

    useEffect(() => {
        getImg();
    }, [])

    useEffect(() => {
        const scene = sceneRef.current;
        const camera = cameraRef.current;
        const renderer = rendererRef.current;

        // 设置渲染器的大小
        renderer.setSize(width, height);
        window.onresize = () => {
            renderer.setSize(window.innerWidth - 100, window.innerHeight - 40);
            camera.aspect = (window.innerWidth - 100) / (window.innerHeight - 40);
            camera.updateProjectionMatrix();
        };
        renderer.setClearColor(0xffffff);
        canvasRef.current.appendChild(renderer.domElement); // 将 DOM 元素和画布结合

        // 设置相机的位置
        camera.position.set(0, 3000, 0);
        camera.lookAt(0, 0, 0); // 观察原点

        // 添加光源
        const light = new THREE.AmbientLight(0xffffff);
        scene.add(light);

        // 添加三维辅助线
        const axesHelper = new THREE.AxesHelper(150);
        scene.add(axesHelper);

        // 渲染循环
        const animate = () => {
            requestAnimationFrame(animate);
            renderer.render(scene, camera); // 渲染场地和相机
        };
        animate();

        return () => {
            renderer.dispose(); // 释放渲染器
        };
    }, []);

    //开关3D
    useEffect(() => {
        const camera = cameraRef.current;
        const renderer = rendererRef.current;
        if (state === 'ok') {
            // 如果状态为 'ok'，则创建 OrbitControls
            controlsRef.current = new OrbitControls(camera, renderer.domElement);
            controlsRef.current.target.set(0, 0, 0); // 围着原点可以三维观察
            controlsRef.current.update(); // 更新控制器
        } else {
            // 如果状态不是 'ok'，则释放控制器
            if (controlsRef.current) {
                controlsRef.current.dispose();
                controlsRef.current = null;
            }
        }
    }, [state]);
    let [lines,setLines]=useState('no')

    // 辅助线
    useEffect(()=>{
        const scene = sceneRef.current;
        if(lines=='ok'){
            Fzx.position.y = -1;
            scene.add(Fzx);
        }else{
            scene.remove(Fzx);
        }
    },[lines])

    const yesbut = () => {
        setShow(false)
        intersectsRef.current = null;
    };

    // 开启图形绘制
    const [paick, setPaick] = useState(false);
    const pikc = () => {
        setPaick(!paick);
    };
    let [show,setShow]=useState(false)
    let onShow=(val)=>{
        setShow(val)
    }
    let [tus,setTus]=useState('no')
    
    const exportGLTF = () => {
        const renderer = rendererRef.current;
        const scene = sceneRef.current;
        const camera = cameraRef.current;

        // 确保场景被渲染
        renderer.render(scene, camera);

        const imageUrl = renderer.domElement.toDataURL("image/png");
        const link = document.createElement("a");
        link.href = imageUrl;
        link.download = "3d_scene.png";
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    };
    
    // const exportGLTF = () => {
    //     const scene = sceneRef.current;
    //     const json = scene.toJSON(); // 将场景转换为 JSON 格式
    //     console.log(json);
    //     const dataStr = JSON.stringify(json, null, 2); // 格式化 JSON 字符串
    //     const blob = new Blob([dataStr], { type: 'application/json' }); // 创建 Blob 对象
    //     const link = document.createElement('a');
    //     link.href = URL.createObjectURL(blob);
    //     link.download = 'scene.json'; // 设置下载文件名
    //     link.click(); // 触发下载
    // };
    // let handleFileChange=(event)=>{
    //     const file = event.target.files[0];
    //     if (file) {
    //         const reader = new FileReader();
    //         reader.onload = (e) => {
    //             const json = JSON.parse(e.target.result); // 解析 JSON 数据
    //             const loader = new THREE.ObjectLoader();
    //             const loadedObject = loader.parse(json); // 使用 ObjectLoader 解析 JSON
    //             sceneRef.current.add(loadedObject); // 将加载的对象添加到场景
    //         };
    //         reader.readAsText(file); // 以文本形式读取文件
    //     }
    // }
    let tokens=()=>{
        console.log(sceneRef.current);
        nav('/door')
    }
    return (
        <>
            <div style={{ width: '100%', height: '4rem', background: 'rgb(8,151,156)', lineHeight:'4rem' }}>
                <p style={{ fontSize: '2rem' }}><ArrowLeft onClick={() => nav("/")} />返回</p> 
            </div>
            <div style={{width:'20rem',height:'10rem',position:'fixed',top:'4rem',right:'10rem',background:'#ff0000',display:tus!='ok'?'none':'inline-block'}}>

                    <img src={tu} alt="" style={{width:'20rem',height:'10rem',}}/>
            </div>
            <div style={{ display: 'flex'}}>
                <div ref={canvasRef}></div>
                <div style={{ width: '10rem',height:'calc(100vh - 4rem)',overflow:'scroll',background:'#00474f',color:'#fff'  }}>
                    <h2>工具栏</h2>
                    <h3 className={`${Zjl.h3}`} style={{display:state=='ok'?'none':'inline-block'}} onClick={() => setState('ok')}>开启3D</h3>
                    <h3 className={`${Zjl.h3}`} style={{display:state!='ok'?'none':'inline-block'}} onClick={() => setState('')}>关闭3D</h3>
                    <h3 className={`${Zjl.h3}`} style={{display:tus=='ok'?'none':'inline-block'}} onClick={() => setTus('ok')}>显示草图</h3>
                    <h3 className={`${Zjl.h3}`} style={{display:tus!='ok'?'none':'inline-block'}} onClick={() => setTus('no')}>关闭草图</h3>
                    <h3 className={`${Zjl.h3}`} style={{display:lines=='ok'?'none':'inline-block'}} onClick={()=>setLines('ok')}>辅助线开</h3>
                    <h3 className={`${Zjl.h3}`} style={{display:lines!='ok'?'none':'inline-block'}} onClick={()=>setLines('no')}>辅助线关</h3>
                    <h3 className={`${Zjl.h3}`} onClick={pikc}>图形绘制</h3>
                    {paick && (
                        <Addkuan 
                            canvasRef={canvasRef} 
                            sceneRef={sceneRef} 
                            cameraRef={cameraRef} 
                            rendererRef={rendererRef}
                            intersectsRef={intersectsRef}
                        />
                    )}
                    
                    <Xuankuan
                        canvasRef={canvasRef}
                        sceneRef={sceneRef} 
                        cameraRef={cameraRef}
                        rendererRef={rendererRef}
                        intersectsRef={intersectsRef}
                        lastTouchX={lastTouchX}
                        lastTouchY={lastTouchY}
                        onShow={onShow}
                    />
                    <div style={{display:show?'flex':'none',flexWrap:'wrap'}}>
                        <Heigths
                            intersectsRef={intersectsRef} 
                            canvasRef={canvasRef}
                            lastTouchY={lastTouchY}
                        />
                        <Widths 
                            intersectsRef={intersectsRef} 
                            canvasRef={canvasRef}
                            lastTouchX={lastTouchX}
                        />
                        <WidthHeigth
                            intersectsRef={intersectsRef}
                            canvasRef={canvasRef}
                            lastTouchX={lastTouchX}
                            lastTouchY={lastTouchY}
                        /> 
                        <Ban 
                            intersectsRef={intersectsRef} 
                            canvasRef={canvasRef}
                            lastTouchY={lastTouchY}
                        />
                    </div>
                    <h3 className={`${Zjl.h3}`} onClick={yesbut}>取消选择</h3>
                    <h3 className={`${Zjl.h3}`} onClick={exportGLTF}>导出结构</h3>
                    <h3 className={`${Zjl.h3}`} onClick={tokens}>测量数据</h3>
                    {/* <input type="file" accept=".json" onChange={handleFileChange} style={{width:'9rem',height:'4rem',background:'chocolate'}} />  */}
                </div>
            </div>
        </>
    );
};

export default App;

